package org.example.ams.es.sample.TestSample;

import javafx.application.Application;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.example.ams.es.sample.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest(classes = Application.class)
public class TestTemplate {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 索引操作
     */

    @Test
    public void createIndex() {
        elasticsearchRestTemplate.indexOps(Student.class).create();
    }

    @Test
    public void deleteIndex() {
        elasticsearchRestTemplate.indexOps(Student.class).delete();
    }

    @Test
    public void existIndex() {
        boolean isExist = elasticsearchRestTemplate.indexOps(Student.class).exists();
    }


    /**
     * 文档操作 CRUD
     */

    @Test
    public void addDocument() {
        Student student = new Student();
        student.setId(1);
        student.setName("cheval");
        student.setAge(18);
        student.setIsMarried(false);
        elasticsearchRestTemplate.save(student);
    }


    @Test
    public void batchAddDocument() {
        Student student1 = new Student();
        student1.setId(1);
        student1.setName("cheval");
        student1.setAge(18);
        student1.setIsMarried(false);

        Student student2 = new Student();
        student2.setId(2);
        student2.setName("mack");
        student2.setAge(18);
        student2.setIsMarried(false);

        List<Student> lists = new ArrayList<>();
        lists.add(student1);
        lists.add(student2);
        elasticsearchRestTemplate.save(lists);
    }

    @Test
    public void deleteDocumentById() {
        elasticsearchRestTemplate.delete("1",Student.class);
    }

    @Test
    public void updateDocument() {
        Map<String,Object> studentInfo = new HashMap<>();
        studentInfo.put("name","jock");
        Document document = Document.from(studentInfo);
        UpdateQuery updateQuery = UpdateQuery.builder("2")
                .withDocument(document)
                .build();

        IndexCoordinates indexCoordinates = IndexCoordinates.of("student");
        elasticsearchRestTemplate.update(updateQuery,indexCoordinates);
    }


    @Test
    public void queryDocumentById() {
        Student student = elasticsearchRestTemplate.get("2", Student.class);
    }


    /**
     * 索引库检索操作
     */
    @Test
    public void searchIndex(){
        // 分页
        Pageable pageable = PageRequest.of(0,10);
        // 排序
        SortBuilder sortBuilder = new FieldSortBuilder("age").order(SortOrder.ASC);
        // name有两种类型： text 和 keyword ,其中name.keyword是指其为keyword类型的字段
        SortBuilder sortBuilder1 = new FieldSortBuilder("name.keyword")
                .order(SortOrder.ASC);
        // 检索条件
        String key = "美丽漂亮";
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name",key))
                .withPageable(pageable)
                .withSorts(sortBuilder,sortBuilder1)
                .build();
        SearchHits<Student> searchHits = elasticsearchRestTemplate.search(searchQuery, Student.class);
        searchHits.getSearchHits();
    }

    /**
     * 高亮搜索
     */
    @Test
    public void highlightSearchIndex(){

        String preTag = "<font color='red'>";
        String postTag = "</font>";
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("name", "美丽可爱"))
                .withHighlightFields(new HighlightBuilder.Field("name")
                        .preTags(preTag)
                        .postTags(postTag))
                .build();

        SearchHits<Student> hits = elasticsearchRestTemplate.search(query, Student.class);
        List<SearchHit<Student>> stuHits = hits.getSearchHits();

        List<Student> hlList = new ArrayList<>();
        for(SearchHit<Student> h : stuHits){
            List<String> hlField = h.getHighlightField("name");
            String hlValue = hlField.get(0);

            Student content = h.getContent();
            content.setName(hlValue);
//            String contentJson = JsonUtils.objectToJson(h.getContent());
//            JsonParser jj = new GsonJsonParser();
//            Map<String, Object> hlMap = jj.parseMap(contentJson);
//            hlMap.put("name", hlValue);
            hlList.add(content);
        }
        System.out.println(hlList);
    }
}
